/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JanelaLogin.java
 *
 * Created on May 30, 2011, 6:17:30 PM
 */
package funcenter.gui;

import funcenter.db.Conexao;
import funcenter.db.DB;
import funcenter.main.Main;
import funcenter.main.Mascara;
import funcenter.main.Usuario;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author arthur
 */
public class JanelaLogin extends javax.swing.JFrame {

    private DB db;
    /** Creates new form JanelaLogin */
    public JanelaLogin() {
        initComponents();
        
        
        db = new DB();
        
        campoUsuario.setDocument(new Mascara(50, false, true));
        campoSenha.setDocument(new Mascara(50));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        botaoCadastrar = new javax.swing.JButton();
        labelUsuario = new javax.swing.JLabel();
        labelSenha = new javax.swing.JLabel();
        campoUsuario = new javax.swing.JTextField();
        campoSenha = new javax.swing.JPasswordField();
        botaoLogar = new javax.swing.JButton();
        logo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                fechando(evt);
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        botaoCadastrar.setText("Cadastrar");
        botaoCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoCadastrar(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(botaoCadastrar, gridBagConstraints);

        labelUsuario.setText("Usuário");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        getContentPane().add(labelUsuario, gridBagConstraints);

        labelSenha.setText("Senha");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        getContentPane().add(labelSenha, gridBagConstraints);

        campoUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                digitar(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(campoUsuario, gridBagConstraints);

        campoSenha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                digitar(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(campoSenha, gridBagConstraints);

        botaoLogar.setText("Logar");
        botaoLogar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoLogar(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 6;
        gridBagConstraints.insets = new java.awt.Insets(15, 5, 10, 5);
        getContentPane().add(botaoLogar, gridBagConstraints);

        logo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/funcenter/images/logo_200x200.png"))); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(20, 20, 20, 20);
        getContentPane().add(logo, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void clicarBotaoLogar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoLogar
        logar();
    }//GEN-LAST:event_clicarBotaoLogar

    private void fechando(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_fechando
        try {
            Conexao.getInstance().fechar();
        } catch(Exception ex){
            Logger.getLogger(JanelaLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_fechando

    private void clicarBotaoCadastrar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoCadastrar
        JanelaCadastroUsuario janela = new JanelaCadastroUsuario(this, true);
        
        janela.setVisible(true);
    }//GEN-LAST:event_clicarBotaoCadastrar

    private void digitar(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_digitar
        if(evt.getKeyChar() == KeyEvent.VK_ENTER){
            logar();
        }
    }//GEN-LAST:event_digitar

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JanelaLogin().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoCadastrar;
    private javax.swing.JButton botaoLogar;
    private javax.swing.JPasswordField campoSenha;
    private javax.swing.JTextField campoUsuario;
    private javax.swing.JLabel labelSenha;
    private javax.swing.JLabel labelUsuario;
    private javax.swing.JLabel logo;
    // End of variables declaration//GEN-END:variables

    private void logar(){
        if(!existemPendencias()){
            String usuario = this.campoUsuario.getText();
            String senha = String.valueOf(this.campoSenha.getPassword());
            if(db.logar(new Usuario(usuario, senha))) {
                this.setVisible(false);
                Main.getJanelaPrincipal().setTitle("Fun Center - " + usuario);
                // Get the size of the screen
                Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

                // Determine the new location of the window
                int w = Main.getJanelaPrincipal().getSize().width;
                int h = Main.getJanelaPrincipal().getSize().height;
                int x = (dim.width-w)/2;
                int y = (dim.height-h)/2;

                // Move the window
                Main.getJanelaPrincipal().setLocation(x, y);
                Main.getJanelaPrincipal().setVisible(true);
            } else {
                JOptionPane.showMessageDialog(this, "Usuário ou senha incorretos");
            }
        }
    }

    private boolean existemPendencias(){
        boolean pendencia = false;

        if(campoUsuario.getText().equals("")){
            JOptionPane.showMessageDialog(this.getContentPane(), "Preencha o campo de usuário");
            pendencia = true;
        } else if(String.valueOf(this.campoSenha.getPassword()).equals("")){
            JOptionPane.showMessageDialog(this.getContentPane(), "Preencha o campo de senha");
            pendencia = true;
        }

        return pendencia;
    }
}
